<script setup>
import axios from "axios";
import {ref} from "vue";

let username = ref("")
let websocket = ref(null);
let state = ref(0)
const friendList = ref([])
const systemBroadCast = ref([])
const textarea=ref();
const isShowMessage=ref(false);
const takeWithUser=ref("");
const chatRecords=ref({})
// 新增：存储上一次的在线用户列表，用于对比上下线
const prevOnlineUsers = ref([]);
const getUsername = async () => {
  const res = await axios({
    url: "http://localhost:8081/user/getUsername",
    withCredentials: true
  })
  username.value = res.data.message
  initWebSocket()
}
const initWebSocket = async () => {
  try {
    const wsUrl = "ws://localhost:8081/chat"
    websocket.value = new WebSocket(wsUrl)
    websocket.value.onopen = (e) => {
      state.value = websocket.value.readyState
      console.log(e)
    }
    websocket.value.onmessage = (e) => {
      // console.log(JSON.parse(e.data))
      const message = JSON.parse(e.data)
      if (message.systemMessage === true) {
        const currentOnline = message.message; // 当前在线用户列表
        // 1. 计算上线用户（当前有，上一次没有）
        const onlineUsers = currentOnline.filter(
            user => !prevOnlineUsers.value.includes(user)
        );
        // 2. 计算下线用户（上一次有，当前没有）
        const offlineUsers = prevOnlineUsers.value.filter(
            user => !currentOnline.includes(user)
        );

        // 3. 生成上线消息
        onlineUsers.forEach(user => {
          systemBroadCast.value.push(`用户${user}已上线`);
        });
        // 4. 生成下线消息
        offlineUsers.forEach(user => {
          systemBroadCast.value.push(`用户${user}已下线`);
        });

        // 5. 更新上一次的在线列表（用于下次对比）
        prevOnlineUsers.value = [...currentOnline];

        //   该部分为好友列表消息
        friendList.value = message.message.filter(item => item != username.value)
      }else {
      //   该部分为用户聊天消息
        const fromUser=message.fromName;
        const content = message.message; // 消息内容
        // 将接收的消息存入对应聊天记录
        if (!chatRecords.value[fromUser]) {
          chatRecords.value[fromUser] = []; // 初始化该用户的聊天记录
        }
        chatRecords.value[fromUser].push({
          from: fromUser,
          content: content,
          time: new Date().toLocaleTimeString()
        });
      }
    }
    // 连接关闭回调
    websocket.value.onclose = () => {
      console.log(3)
      console.log("WebSocket连接关闭");
    };

  } catch (error) {
    console.error("建立WebSocket连接失败:", error)
  }
}

const onClick=(row,column,event)=>{
  console.log(row)
  console.log(column)
  console.log(event)
  isShowMessage.value=true
  takeWithUser.value=row
}
const sendMessage=()=>{
  if(!takeWithUser.value){
    alert("请先选择聊天对象");
    return;
  }
  // 验证：消息内容不能为空
  const content = textarea.value.trim();
  if (!content) {
    alert("消息内容不能为空");
    return;
  }
  // 验证：WebSocket连接必须已建立
  if (!websocket.value || websocket.value.readyState !== WebSocket.OPEN) {
    alert("WebSocket未连接，请稍后重试");
    return;
  }
  // 构造发送格式（后端要求：{toName: 接收者, message: 内容}）
  const sendData={
    toName:takeWithUser.value,
    message:content
  }
  // 发送消息
  websocket.value.send(JSON.stringify(sendData));
  if (!chatRecords.value[takeWithUser.value]) {
    chatRecords.value[takeWithUser.value] = []; // 初始化该用户的聊天记录
  }
  chatRecords.value[takeWithUser.value].push({
    from:username.value,
    content:content,
    time:new Date().toLocaleTimeString()
  })
  // 清空输入框
  textarea.value = "";
}
getUsername();
</script>

<template>
  <div>
    <el-container>
      <el-header>
        <div>当前用户：{{ username }}</div>
        <div>当前websocket:{{ state === 1 ? "已连接" : "未连接" }}</div>
      </el-header>
      <el-container>
        <el-aside>
          <el-table style="min-height: 30vh" :data="friendList" @row-click="onClick">
            <el-table-column label="好友列表">
              <template #default="{row}">
                <div>{{ row }}</div>
              </template>
            </el-table-column>

          </el-table>
          <el-table style="min-height: 30vh" :data="systemBroadCast">
            <el-table-column label="系统广播">
              <template #default="{row}">
                <div>{{ row }}</div>
              </template>
            </el-table-column>

          </el-table>
        </el-aside>
        <el-main v-if="isShowMessage">
<!--          聊天消息展示框-->
          <div class="show-message" >
            <span style="background-color:rgb(225, 243, 216);width: 100%;display: inline-block">正在和{{takeWithUser}}聊天</span>
            <!-- 聊天记录列表 -->
            <div class="message-list">
              <div v-for="(msg,index) in chatRecords[takeWithUser]" :key="index" class="message-item" :class="{'self-message':msg.from===username}">
                <span class="sender">{{ msg.from }} {{ msg.time }}:</span>
                <span class="content">{{ msg.content }}</span>
              </div>
            </div>
          </div>
<!--          消息输入框-->
          <div>
            <el-input v-model="textarea" type="textarea" placeholder="请输入聊天消息"  autosize ></el-input>
            <el-button type="success" @click="sendMessage">发送</el-button>
          </div>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<style scoped>
.el-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
:deep(.el-textarea){
  min-height: 150px;
}
:deep(.el-textarea textarea){
  min-height: 100%;
}
.show-message{
  height: calc(100% - 190px);
  background-color: rgb(217, 236, 255);
}
:deep(main.el-main){
  height: calc(100vh - 60px);
}
.show-message {
  height: calc(100% - 190px);
  background-color: rgb(217, 236, 255);
  display: flex;
  flex-direction: column;
}

.message-list {
  flex: 1;
  padding: 10px;
  overflow-y: auto; /* 消息过多时滚动 */
}

.message-item {
  margin: 8px 0;
  padding: 0 10px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.message-item.self-message{
  align-items: flex-end;
}

/* 自己发送的消息样式 */
.self-message .content {
  background-color: #e1f3d8; /* 浅绿色 */
  float: right;
}

/* 对方发送的消息样式 */
.message-item:not(.self-message) .content {
  background-color: #ffffff; /* 白色 */
  float: left;
}

.sender {
  font-size: 12px;
  color: #666;
  //display: block;
  margin-bottom: 4px;
}

.content {
  padding: 6px 10px;
  border-radius: 6px;
  max-width: 70%;
  word-wrap: break-word; /* 自动换行 */
}
</style>